﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Camelot.SharePointIntegration.IntegrationService
{
    public sealed class ServicePluginManager
    {
        private ServicePluginManager() {}

        public static ServicePluginResult ExecuteTask(Entities.Task task)
        {
            var assemblyQualifiedName = task.Plugin.TypeName;

            var type = Type.GetType(assemblyQualifiedName, false, true);
            if (type == null)
                throw new Exception(String.Format("Plugin could not be loaded from assembly qualified name '{0}'", assemblyQualifiedName));


            if (!typeof(IServicePlugin).IsAssignableFrom(type))
                throw new Exception(String.Format("Plugin '{0}' cannot be used with this service", type.Name));

            IServicePlugin instance = (IServicePlugin)Activator.CreateInstance(type);
            var result = instance.Execute(task);

            if (instance is IDisposable)
                ((IDisposable)instance).Dispose();

            return result;
        }
    }
}
